﻿using Common.Tools.Model;
using Newtonsoft.Json;
using RestSharp;

namespace Common.Tools
{
    /// <summary>
    ///  Rest客户端帮助类
    /// </summary>
    public static class RestClientHelper
    {
        /// <summary>
        /// 发送post请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="data">请求数据</param>
        /// <param name="contentType">头部</param>
        /// <param name="headers">头部</param>
        /// <returns></returns>
        public static async Task<ResposeModel> PostAsync(string url, string data, Dictionary<string, string>? headers = null, string contentType = "application/json")
        {
            try
            {
                using var client = new RestClient();
                var request = new RestRequest(url, Method.Post)
                {
                    Timeout = TimeSpan.FromSeconds(60),
                };
                request.AddHeader("Content-Type", contentType);
                if (headers != null && headers.Any())
                {
                    foreach (var item in headers)
                    {
                        request.AddHeader(item.Key, item.Value);
                    }
                }

                request.AddStringBody(data, DataFormat.Json);
                var response = await client.ExecuteAsync(request);
                var status = response?.StatusCode ?? System.Net.HttpStatusCode.InternalServerError;
                return new ResposeModel()
                {
                    Code = (int)status,
                    Message = status == System.Net.HttpStatusCode.OK ? response?.Content : $"{response?.StatusDescription}{response?.ErrorMessage}"
                };
            }
            catch (Exception ex)
            {
                LogHelper.Error($"PostAsync请求接口异常：url={url}," +
                    $"content={JsonConvert.SerializeObject(data)}," +
                    $"ex={JsonConvert.SerializeObject(ex)}");
                return new ResposeModel() { Code = 500, Message = $"请求接口异常：{ex.Message}" };
            }
        }

        /// <summary>
        /// 发送Get请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="data">数据</param>
        /// <param name="headers">头部</param>
        /// <returns></returns>
        public static async Task<ResposeModel> GetAsync(string url, Dictionary<string, string>? data = null, Dictionary<string, string>? headers = null, string contentType = "text/plain")
        {
            try
            {
                if (data != null && data.Count > 0)
                {
                    url += "?";
                    foreach (var item in data)
                    {
                        url += $"{item.Key}={item.Value}&";
                    }

                    url = url.TrimEnd('&');
                }

                using var client = new RestClient();
                var request = new RestRequest(url)
                {
                    Timeout = TimeSpan.FromSeconds(60),
                };
                request.AddHeader("Content-Type", contentType);
                if (headers != null && headers.Any())
                {
                    foreach (var item in headers)
                    {
                        request.AddHeader(item.Key, item.Value);
                    }
                }

                var response = await client.ExecuteAsync(request);
                var status = response?.StatusCode ?? System.Net.HttpStatusCode.InternalServerError;
                return new ResposeModel()
                {
                    Code = (int)status,
                    Message = status == System.Net.HttpStatusCode.OK ? response?.Content : $"{response?.StatusDescription}{response?.ErrorMessage}"
                };
            }
            catch (Exception ex)
            {
                LogHelper.Error($"GetAsync请求接口异常：url={url}," +
                    $"content={JsonConvert.SerializeObject(data ?? new Dictionary<string, string>())}," +
                    $"ex={JsonConvert.SerializeObject(ex)}");
                return new ResposeModel() { Code = 500, Message = $"请求接口异常：{ex.Message}" };
            }
        }

        /// <summary>
        /// post FormData请求
        /// </summary>
        /// <param name="url">请求路由</param>
        /// <param name="strParam">字符串请求参数</param>
        /// <param name="fileParam">文件请求参数</param>
        /// <param name="headers">头部</param>
        /// <returns></returns>
        public static async Task<ResposeModel> PostFormDataAsync(string url, Dictionary<string, string>? strParam = null, Dictionary<string, byte[]>? fileParam = null, Dictionary<string, string>? headers = null)
        {
            try
            {
                var client = new RestClient();
                var request = new RestRequest(url, Method.Post)
                {
                    AlwaysMultipartFormData = true,
                    Timeout = TimeSpan.FromSeconds(60),
                };
                if (headers != null && headers.Any())
                {
                    foreach (var item in headers)
                    {
                        request.AddHeader(item.Key, item.Value);
                    }
                }

                const int i = 0;
                if (fileParam != null && fileParam.Any())
                {
                    foreach (var item in fileParam)
                    {
                        request.AddFile(item.Key, item.Value, $"file{i}");
                    }
                }

                if (strParam != null && strParam.Any())
                {
                    foreach (var item in strParam)
                    {
                        request.AddParameter(item.Key, item.Value);
                    }
                }

                var response = await client.ExecuteAsync(request);
                var status = response?.StatusCode ?? System.Net.HttpStatusCode.InternalServerError;
                return new ResposeModel()
                {
                    Code = (int)status,
                    Message = status == System.Net.HttpStatusCode.OK ? response?.Content : $"{response?.StatusDescription}{response?.ErrorMessage}"
                };
            }
            catch (Exception ex)
            {
                LogHelper.Error($"请求FormData接口异常：url={url}," +
                    $"content={JsonConvert.SerializeObject(strParam ?? new Dictionary<string, string>())}," +
                    $"headers={JsonConvert.SerializeObject(headers ?? new Dictionary<string, string>())}," +
                    $"ex={JsonConvert.SerializeObject(ex)}");
                return new ResposeModel() { Code = 500, Message = $"请求接口异常：{ex.Message}" };
            }
        }
    }
}